""" 

    Like.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which registers whether a user likes or dislikes something
    about a legislator and returns the data as a JSON object.  A user must be logged into Facebook to use this service.

    Accepts two parameters:
        legislator (required) - bioguide_id for the legislator
        like (required) - true or false
    
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from sets import Set
from django.utils import simplejson
from facebook import FacebookError
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from utils import fbUtil, dbUtil, UserLikes

class MainHandler(webapp.RequestHandler):
    
    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "like":None}
        
        try:
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
            if self.facebookapi is None:
                jsonOutput["result"] = "error"
                jsonOutput["message"] = "not logged in"
            else:
                uid = int(self.facebookapi.uid)
                legislator = self.request.get('legislator', default_value=None)
                like = self.request.get('like', default_value=None)
                if (legislator is None) or (like is None):
                    jsonOutput["result"] = "error"
                    jsonOutput["message"] = "missing parameters"
                else:
                    likeRecord = UserLikes.get_or_insert(legislator+"_"+str(uid), uid=uid, legislator=legislator)
                    likeRecord.like = (str.lower(str(like)) != "false")
                    likeRecord.put()
                    jsonOutput["like"] = like
                    jsonOutput["legislator"] = legislator
                 
                    fbStory = {"legislator_id": legislator, "legislator_name": const.FRIENDLY_NAME[legislator]}
                    if (str.lower(str(like)) != "false"):
                        fbStory["like"] = "likes"
                        jsonOutput["response"] = "You now like " + const.FRIENDLY_NAME[legislator]
                    else:
                        fbStory["like"] = "does not like"
                        jsonOutput["response"] = "You now do not like " + const.FRIENDLY_NAME[legislator]
                    self.facebookapi.feed.publishUserAction("54614982770", fbStory)
                    
            
        except FacebookError, e:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = str(e.msg)
                       
        self.response.out.write(simplejson.dumps(jsonOutput))          
  
def main():
	application = webapp.WSGIApplication([('/fb/like', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
